package com.github.pig.goods.bussiness.product.controller;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.util.SignUtils;
import com.github.pig.goods.bussiness.product.entity.TAgent;
import com.github.pig.goods.bussiness.product.entity.TOrder;
import com.github.pig.goods.bussiness.product.entity.TOrderProduct;
import com.github.pig.goods.bussiness.product.entity.VoOrder;
import com.github.pig.goods.bussiness.product.service.ITAgentService;
import com.github.pig.goods.bussiness.product.service.ITOrderProductService;
import com.github.pig.goods.bussiness.product.service.ITOrderService;
import com.github.pig.goods.bussiness.product.service.ITShopCarService;
import com.github.pig.goods.common.util.pay.WxPay;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.plugins.Page;


import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.Query;
import com.github.pig.common.util.R;
import com.github.pig.common.web.BaseController;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import sun.management.Agent;

import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.locks.Condition;

/**
 * <p>
 * 订单主表 前端控制器
 * </p>
 *
 * @author tao123
 * @since 2018-09-13
 */
@Slf4j
@Api(value = "TOrderController", description = "订单主表")
@RestController
@RequestMapping("/order")
public class TOrderController extends BaseController{


    @Autowired
    private ITOrderService tOrderService;

    @Autowired
    private ITOrderProductService tOrderProductService;

    @Autowired
    private WxPayService payService;


    @Autowired
    private ITShopCarService tShopCarService;


    @Autowired
    private ITAgentService tAgentService;
/**
 * 通过ID查询
 *
 * @param id ID
 * @return TOrder
 */
@GetMapping("/{id}")
@ApiOperation(value = "  按id查询", httpMethod = "GET", notes = "  按id查询")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "long", paramType = "path")
public R<VoOrder> get(@PathVariable String id){
    Map<String, Object> params = new HashMap<>();
    params.put(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
    params.put("id",id);
    Page orderPage = tOrderService.selectOrderForMobile(new Query<>(params));

    return  new R<>((VoOrder)orderPage.getRecords().get(0));
}


/**
* 分页查询信息
*
* @param params 分页对象
* @return 分页对象
*/
@RequestMapping("/page")
@ApiOperation(value = "分页查询 参数为TOrder表中的属性", notes = "TOrder列表方法")
@ApiImplicitParam(name = "查询参数", value = "TOrder参数", required = true, dataType = "Map", paramType = "path")
public Page page(@RequestParam Map<String, Object> params){
    params.put(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
    return tOrderService.selectWithOrderPage(new Query<>(params));
    //return tOrderService.selectPage(new Query<>(params),new EntityWrapper<>());
}


    /**
     * 分页查询信息
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @RequestMapping("/mobile/page")
    @ApiOperation(value = "分页查询 参数为TOrder表中的属性", notes = "TOrder列表方法")
    @ApiImplicitParam(name = "查询参数", value = "TOrder参数", required = true, dataType = "Map", paramType = "path")
    public Page pageForMobile(@RequestParam Map<String, Object> params){
        params.put(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        Page orderPage = tOrderService.selectOrderForMobile(new Query<>(params));
        orderPage.setTotal(orderPage.getRecords().size());
        return  orderPage;
    }

/**
 * 添加
 * @param  tOrder 实体
 * @return success/false
 */
@PostMapping("/add")
@ApiOperation(value = "新增实体 参数为TOrder实体", notes = "TOrder新增方法")
@ApiImplicitParam(name = "tOrder", value = "TOrder实体", required = true, dataType = "TOrder", paramType = "path")
public R<WxPay> add(@RequestBody VoOrder tOrder) throws Exception{


    log.info("下单前段请求详细信息："+tOrder.toString());
    //TODO 设计订单号
    String id = String.valueOf(System.currentTimeMillis());

    //支付金额
    Integer orderAmountPayable=0;
    List<TOrderProduct> products = tOrder.getProductList();

    for (int i=0;i<products.size();i++){
        products.get(i).setOrderId(id);
        products.get(i).setCreateTime(new Date());
        orderAmountPayable += products.get(i).getPrice() * products.get(i).getQuantity();
    }

    tOrderProductService.insertBatch(products);

    tOrder.setId(id);

    WxPayUnifiedOrderRequest request = WxPayUnifiedOrderRequest.newBuilder()
            .body("快易布支付")
            .totalFee(orderAmountPayable)
            .totalFee(tOrder.getOrderAmountPayable())
            .spbillCreateIp("123.207.241.55")
            .notifyUrl("http://123.207.241.55:9997/goods/pay/notify/order")
            .tradeType(WxPayConstants.TradeType.JSAPI)
            .openid(tOrder.getOpenId())
            .outTradeNo(tOrder.getId())
            .build();
    request.setSignType(WxPayConstants.SignType.MD5);
    WxPayUnifiedOrderResult result = this.payService.unifiedOrder(request);
    this.logger.info(result.toString());
    this.logger.warn(this.payService.getWxApiData().toString());

    tOrder.setPrepayId(result.getPrepayId());
    tOrder.setStatus("0");
    tOrder.setCreatedTime(new Date());
    tOrder.setRebateStatus("0");
    tOrder.setOrderAmountPayable(orderAmountPayable);
    tOrder.setPaymentMethod("0");
    tOrder.setPaymentChannel("0");
    if (tOrder.getAgent()==null){
        tOrder.setAgent(TAgent.builder().sn("0000").build());
        tOrder.setRebateStatus("0");
        tOrder.setRebateTotal(0.00);
    }else{
        TAgent a = tAgentService.selectOne(com.baomidou.mybatisplus.mapper.Condition.create().eq("sn",tOrder.getAgent().getSn()));
        Double diPer;
        if (a == null) {
            diPer = 1.00;
        }else{
            diPer = tOrder.getAgent().getDiPer();
        }
        tOrder.setAgent(a);
        tOrder.setRebateStatus("1");
        tOrder.setRebateTotal((Double.valueOf(orderAmountPayable))*diPer);
    }


    boolean tag =tOrderService.insert(tOrder);

    if (tag == true) {

        //String orderParam = JSONObject.toJSONString(result);

        //清空购物车
        if (tOrder.getAccountId() == null) {
            return new R<>(null,"下单失败！AccountId为空");
        }else{
            Boolean deleteTag =tShopCarService.delete(com.baomidou.mybatisplus.mapper.Condition.create().eq("account_id",tOrder.getAccountId()));
            log.info("清空购物车：{}",deleteTag);
        }

        Map map  = new HashMap();
        map.put("appId",result.getAppid());
        map.put("nonceStr",result.getNonceStr());
        map.put("package","prepay_id="+result.getPrepayId());
        map.put("signType","MD5");
        map.put("timeStamp",String.valueOf(System.currentTimeMillis() / 1000L));
        map.put("key","QmnbW12kil9Usdg2TR1ljh81Y1MMP1rw");
        String sign = SignUtils.createSign(map,"QmnbW12kil9Usdg2TR1ljh81Y1MMP1rw");

        WxPay pay =WxPay.builder().paySign(sign).nonceStr(result.getNonceStr()).timeStamp((String) map.get("timeStamp")).prepayId((String) map.get("package")).build();
        log.info("微信返回参数：{}",pay);
        return new R<>(pay,"下单成功");
    }else {
        return new R<>(null,"下单失败！");
    }

}

/*
    public static void main(String[] args) {
        Map map  = new HashMap();
        map.put("appId","wx6178dfa0adaf26f9");
        map.put("nonceStr","AnQnHhZSlsfPJ3RW");
        map.put("package","prepay_id="+"wx251643413441238f88088d492292869060");
        map.put("signType","MD5");
        map.put("timeStamp",String.valueOf(System.currentTimeMillis() / 1000L));
        map.put("key","QmnbW12kil9Usdg2TR1ljh81Y1MMP1rw");
        String sign = SignUtils.createSign(map,"QmnbW12kil9Usdg2TR1ljh81Y1MMP1rw");

        WxPay pay =WxPay.builder().paySign(sign).nonceStr((String) map.get("nonceStr")).timeStamp((String) map.get("timeStamp")).prepayId((String) map.get("package")).build();
        System.out.println("返回参数："+pay.toString());
    }
*/


/**
 * 删除
 * @param id ID
 * @return success/false
 */
@DeleteMapping("/{id}")
@ApiOperation(value = "按id删除", notes = "TOrder删除")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "long", paramType = "path")
public R<Boolean> delete(@PathVariable String id){return new R<>(tOrderService.deleteById(id));}

/**
 * 编辑
 * @param  tOrder 实体
 * @return success/false
 */
@PutMapping("/update")
@ApiOperation(value = "修改 参数为TOrder实体", notes = "TOrder修改")
@ApiImplicitParam(name = "tOrder", value = "TOrder实体", required = true, dataType = "TOrder", paramType = "path")
public R<Boolean> edit(@RequestBody TOrder tOrder){
    tOrder.setUpdateTime(new Date());

    return new R<>(tOrderService.updateById(tOrder));
}


}
